package com.example.springboot.utils;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: 09-springboot-websocket
 * @description: WebSocketsUtils
 * @author: Yuwl
 * @create: 2019-11-25 15:43
 **/
public class WebSocketUtils {

	public static final Map<String, Session> LIVING_SESSION_CACHE = new ConcurrentHashMap<>();

	public static void sendMessageAll (String message) {
		LIVING_SESSION_CACHE.forEach((sessionId, session) -> sendMessage(session, message));
	}

	public static void sendMessage(Session session, String message) {
		if (session == null) {
			return;
		}
		RemoteEndpoint.Basic basic = session.getBasicRemote();
		if (basic == null) {
			return;
		}
		try {
			basic.sendText(message, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
